//
// Created by 33145 on 2023/6/3.
//
#include "../rocket/tcp/tcp_server.h"
#include "../rocket/tcp/net_addr.h"
#include <memory>
#include <pthread.h>
#include "cstring"
#include "../rocket/common/rocket.h"
#include "../rocket/tcp/tcp_client.h"
#include "../rocket/coder/string_coder.h"

void test_connect() {

  // 调用 conenct 连接 server
  // wirte 一个字符串
  // 等待 read 返回结果

  int fd = socket(AF_INET, SOCK_STREAM, 0);

  if (fd < 0) {
    LOG_ERROR("invalid fd %d", fd);
    exit(0);
  }

  sockaddr_in server_addr;
  memset(&server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(12345);
  inet_aton("127.0.0.1", &server_addr.sin_addr);

  int rt = connect(fd, reinterpret_cast<sockaddr*>(&server_addr), sizeof(server_addr));

  LOG_DEBUG("connect success");

  std::string msg = "hello rocket!";

  rt = write(fd, msg.c_str(), msg.length());

  LOG_DEBUG("success write %d bytes, [%s]", rt, msg.c_str());

  char buf[100];
  rt = read(fd, buf, 100);
  LOG_DEBUG("success read %d bytes, [%s]", rt, std::string(buf).c_str());

}

void test_tcp_client() {
  rocket::IPNetAddr::ptr addr = std::make_shared<rocket::IPNetAddr>("127.0.0.1", 12345);
  rocket::TCPClient::ptr client = std::make_shared<rocket::TCPClient>(addr);
  client->connect([addr, client](){
    LOG_DEBUG("connect to [%s] success", addr->toString().c_str());
    rocket::StringProtocol::ptr message = std::make_shared<rocket::StringProtocol>("hello world");
    message->setReqId("962464");
    client->writeMessage(message, [](rocket::AbstractProtocol::ptr msg_ptr) {
      LOG_DEBUG("send message success : ID: [%s]", msg_ptr->getReqId().c_str());
    });
    client->readMessage("123456", [](rocket::AbstractProtocol::ptr msg_ptr) {
      auto msg = std::dynamic_pointer_cast<rocket::StringProtocol>(msg_ptr);
      LOG_DEBUG("req_id : [%s] -- get response [%s]", msg->getReqId().c_str(), msg->info.c_str());
    });
    client->writeMessage(message, [](rocket::AbstractProtocol::ptr msg_ptr) {
      LOG_DEBUG("send message succ222ess : ID: [%s]", msg_ptr->getReqId().c_str());
    });
  });
}

int main() {
  rocket::Config::SetGlobalConfig("/home/orange/tinytinyRPC/conf/client.xml");
  rocket::Logger::InitGlobalLogger(0);

  // test_connect();
  test_tcp_client();
}